#define CATCH_CONFIG_RUNNER
#include "mpiH_Init.hpp"
#include "mpiH_Comm.hpp"
#include <catch2/catch_test_macros.hpp>
#include <sstream>

int main( int argc, char* argv[] ) {
	MPI_Init_H autoInit { argc, argv }; // calls MPI_Finalize() on destruction

	MPI_Comm_H comm { MPI_COMM_WORLD };

	std::stringstream ss;
	ss << "Rank ";
	ss.width(2);
	ss << std::right << comm.rank() << ":\n";

	std::streambuf* cout_buf;

	/* save old buffer and redirect output to string stream */
	if ( !comm.isMaster() )
		cout_buf = std::cout.rdbuf( ss.rdbuf() );
	else
		std::cout << ss.str();
	
	int result = Catch::Session().run( argc, argv );

	/* reset buffer */
	if ( !comm.isMaster() )
		std::cout.rdbuf( cout_buf );

	// std::stringstream printRank;
	// printRank << "Rank ";
	// printRank.width(2);
	// printRank << std::right << comm.rank() << ":\n";

	for ( int i{1}; i<comm.size(); ++i ){
		MPI_Barrier(comm);
		if ( i == comm.rank() ){
			/* if all tests are passed, it's enough if we hear that from 
			 * the master. Otherwise, print results */
			if ( ss.str().rfind("All tests passed") == std::string::npos )
				// std::cout << printRank.str() + ss.str();
				std::cout << ss.str();
		}
	}
	// /* have master print last, because it's the one with the most assertions */
	// MPI_Barrier(comm);
	// if ( comm.isMaster() )
	// 	std::cout << printRank.str() + ss.str();

	return result;
}